# -*- coding: utf-8 -*-
import datetime, re

from peewee import *
from basemodel import BaseModel

from server.wechatlib import WeChatApi


class WeChat(BaseModel):
    appid = CharField()
    secret = CharField()
    token = CharField()
    token_expires = IntegerField(default=0)
    token_time = DateTimeField(default=datetime.datetime.now)
    jsticket = CharField()
    jsticket_expires = IntegerField(default=0)
    jsticket_time = DateTimeField(default=datetime.datetime.now)
    noncestr = CharField()

    def get_token(self):
        if datetime.datetime.now() - self.token_time > datetime.timedelta(seconds=7200):
            api = WeChatApi()
            self.token_time = datetime.datetime.now()
            self.token = api.get_token(self.appid, self.secret)
            self.save()
        return self.token

    def get_jsticket(self):
        if datetime.datetime.now() - self.jsticket_time > datetime.timedelta(seconds=7200):
            api = WeChatApi()
            self.jsticket_time = datetime.datetime.now()
            self.jsticket = api.get_jsticket(self.get_token())
            self.save()
        return self.jsticket